/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller.CoreServlet;

import Model.BeanUltility.ResultsetMapper;
import Model.DataUltility.DatabaseConnector;
import Model.ObjectBean.ViewBean.PersonalInfo_FrDatabase;
import Model.ObjectBean.ViewBean.UserAccount_FrDatabase;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Tran Nguyen Anh Tu
 */
public class ChangePasswordServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

        PrintWriter out = resp.getWriter();

        String oldpassDTB; //current password from database
        String oldpass=req.getParameter("oldpassword");
        String newpass=req.getParameter("newpassword");
        String confirmpass=req.getParameter("confirmpassword");      
        String userID=((PersonalInfo_FrDatabase)req.getSession().getAttribute("perInfo")).getId();
        String selectQuerry="select * from login_account where id='"+userID+"'";
        String updateQuerry="";
        String message="";
        //
        
        UserAccount_FrDatabase user = new UserAccount_FrDatabase();           
        try
        {
            ResultsetMapper.mapperResultsettoObject(DatabaseConnector.getResultSet(selectQuerry),
                                                    UserAccount_FrDatabase.class,  user);
        }
        catch(Exception e){System.out.print(e);}
        oldpassDTB=user.getPassw();
        //
        
        if(!oldpass.equals(oldpassDTB))
        {
            message+="Mật khẩu cũ không hợp lệ<br/>";
        }
        else if(!newpass.equals(confirmpass))
        {
            message+="Mật khẩu mới không khớp<br/>";
        }
        else
        {
            message+="Thay đổi mật khẩu thành công<br/>";
            updateQuerry+="update login_account set passw='"+newpass+"' where id='"+userID+"'";
            DatabaseConnector.executeQueryString(updateQuerry);
            System.out.print("update password succesful");
        }
        req.setAttribute("message",message);
        RequestDispatcher dispatcher=req.getRequestDispatcher("WEB-INF/MainJSP/changepass.jsp");
        dispatcher.forward(req, resp);
        
    }

    
}
